<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 *  XJ_Input Class
 *
 *  Pre-processes global input data for security
 *
 *  @package		XJPHP
 *  @subpackage	Libraries
 *  @category	Input
 */
if ( ! class_exists('XJ_Input')) {
    class XJ_Input
    {
        /**
         * IP address of the current user
         *
         * @var	string
         */
        protected $ip_address = FALSE;

        /**
         * Allow GET array flag
         *
         * If set to FALSE, then $_GET will be set to an empty array.
         *
         * @var	bool
         */
        protected $_allow_get_array = TRUE;

        /**
         * Standardize new lines flag
         *
         * If set to TRUE, then newlines are standardized.
         *
         * @var	bool
         */
        protected $_standardize_newlines;
        /**
         * Enable CSRF flag
         *
         * Enables a CSRF cookie token to be set.
         * Set automatically based on config setting.
         *
         * @var	bool
         */
        protected $_enable_csrf = FALSE;

        /**
         * List of all HTTP request headers
         *
         * @var array
         */
        protected $headers = array();

        /**
         * Raw input stream data
         *
         * Holds a cache of php://input contents
         *
         * @var	string
         */
        protected $_raw_input_stream;

        /**
         * Parsed input stream data
         *
         * Parsed from php://input at runtime
         *
         * @see	XJ_Input::input_stream()
         * @var	array
         */
        protected $_input_stream;

        protected function _fetch_from_array(&$array, $index = NULL){
            $value = NULL;
            isset($index) OR $index = array_keys($array);
            if (is_array($index))
            {
                $output = array();
                foreach ($index as $key)
                {
                    $output[$key] = $this->_fetch_from_array($array, $key);
                }
                return $output;
            }
            if (isset($array[$index]))
            {
                $value = $array[$index];
            }
            return $value;
        }

        public function get($index = NULL){
            return $this->_fetch_from_array($_GET, $index);
        }
        public function post($index = NULL){
            return $this->_fetch_from_array($_POST, $index);
        }
        public function post_get($index){
            return isset($_POST[$index])
                ? $this->post($index)
                : $this->get($index);
        }
        public function get_post($index)
        {
            return isset($_GET[$index])
                ? $this->get($index)
                : $this->post($index);
        }
        public function value($index, $return_false = FALSE){
            $value = NULL;
            if(isset($_GET[$index])){
                $value = $this->get($index);
            }elseif (isset($_POST[$index])){
                $value = $this->post($index);
            }elseif (isset($_COOKIE[$index])){
                $value = $this->cookie($index);
            }else{
                $value = $this->input_stream($index);
            }
            if (isset($value) === FALSE && $return_false){
                return FALSE;
            }
            return $value;
        }
        public function all_value(){
            $values = array();
            $values['GET'] = $_GET;
            $values['POST'] = $_POST;
            $values['COOKIE'] = $_COOKIE;
            $values['STREAM'] = $this->_raw_input_stream;
            return $values;
        }
        public function cookie($index = NULL)
        {
            return $this->_fetch_from_array($_COOKIE, $index);
        }
        public function server($index)
        {
            return $this->_fetch_from_array($_SERVER, $index);
        }
        public function input_stream($index = NULL)
        {
            // Prior to PHP 5.6, the input stream can only be read once,
            // so we'll need to check if we have already done that first.
            if ( ! is_array($this->_input_stream))
            {
                // $this->raw_input_stream will trigger __get().
                parse_str($this->raw_input_stream, $this->_input_stream);
                is_array($this->_input_stream) OR $this->_input_stream = array();
                $json = json_decode($this->_raw_input_stream, TRUE);
                if (is_array($json) && count($json)){
                    $this->_input_stream = array_merge($this->_input_stream, $json);
                }
            }

            return $this->_fetch_from_array($this->_input_stream, $index);
        }
        /**
         * Set cookie
         *
         * Accepts an arbitrary number of parameters (up to 7) or an associative
         * array in the first parameter containing all the values.
         *
         * @param	string|mixed[]	$name		Cookie name or an array containing parameters
         * @param	string		$value		Cookie value
         * @param	int		$expire		Cookie expiration time in seconds
         * @param	string		$domain		Cookie domain (e.g.: '.yourdomain.com')
         * @param	string		$path		Cookie path (default: '/')
         * @param	string		$prefix		Cookie name prefix
         * @param	bool		$secure		Whether to only transfer cookies via SSL
         * @param	bool		$httponly	Whether to only makes the cookie accessible via HTTP (no javascript)
         * @return	void
         */
        public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = FALSE)
        {
            if (is_array($name))
            {
                // always leave 'name' in last place, as the loop will break otherwise, due to $$item
                foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') as $item)
                {
                    if (isset($name[$item]))
                    {
                        $$item = $name[$item];
                    }
                }
            }

            if ($prefix === '' && config_item('cookie_prefix') !== '')
            {
                $prefix = config_item('cookie_prefix');
            }

            if ($domain == '' && config_item('cookie_domain') != '')
            {
                $domain = config_item('cookie_domain');
            }

            if ($path === '/' && config_item('cookie_path') !== '/')
            {
                $path = config_item('cookie_path');
            }

            if ($secure === FALSE && config_item('cookie_secure') === TRUE)
            {
                $secure = config_item('cookie_secure');
            }

            if ($httponly === FALSE && config_item('cookie_httponly') !== FALSE)
            {
                $httponly = config_item('cookie_httponly');
            }

            if ( ! is_numeric($expire))
            {
                $expire = time() - 86500;
            }
            else
            {
                $expire = ($expire > 0) ? time() + $expire : 0;
            }

            setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly);
        }
        /**
         * Fetch the IP Address
         *
         * Determines and validates the visitor's IP address.
         *
         * @return	string	IP address
         */
        public function ip_address()
        {
            if ($this->ip_address !== FALSE)
            {
                return $this->ip_address;
            }

            $proxy_ips = config_item('proxy_ips');
            if ( ! empty($proxy_ips) && ! is_array($proxy_ips))
            {
                $proxy_ips = explode(',', str_replace(' ', '', $proxy_ips));
            }

            $this->ip_address = $this->server('REMOTE_ADDR');

            if ($proxy_ips)
            {
                foreach (array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP') as $header)
                {
                    if (($spoof = $this->server($header)) !== NULL)
                    {
                        // Some proxies typically list the whole chain of IP
                        // addresses through which the client has reached us.
                        // e.g. client_ip, proxy_ip1, proxy_ip2, etc.
                        sscanf($spoof, '%[^,]', $spoof);

                        if ( ! $this->valid_ip($spoof))
                        {
                            $spoof = NULL;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                if ($spoof)
                {
                    for ($i = 0, $c = count($proxy_ips); $i < $c; $i++)
                    {
                        // Check if we have an IP address or a subnet
                        if (strpos($proxy_ips[$i], '/') === FALSE)
                        {
                            // An IP address (and not a subnet) is specified.
                            // We can compare right away.
                            if ($proxy_ips[$i] === $this->ip_address)
                            {
                                $this->ip_address = $spoof;
                                break;
                            }

                            continue;
                        }

                        // We have a subnet ... now the heavy lifting begins
                        isset($separator) OR $separator = $this->valid_ip($this->ip_address, 'ipv6') ? ':' : '.';

                        // If the proxy entry doesn't match the IP protocol - skip it
                        if (strpos($proxy_ips[$i], $separator) === FALSE)
                        {
                            continue;
                        }

                        // Convert the REMOTE_ADDR IP address to binary, if needed
                        if ( ! isset($ip, $sprintf))
                        {
                            if ($separator === ':')
                            {
                                // Make sure we're have the "full" IPv6 format
                                $ip = explode(':',
                                    str_replace('::',
                                        str_repeat(':', 9 - substr_count($this->ip_address, ':')),
                                        $this->ip_address
                                    )
                                );

                                for ($j = 0; $j < 8; $j++)
                                {
                                    $ip[$j] = intval($ip[$j], 16);
                                }

                                $sprintf = '%016b%016b%016b%016b%016b%016b%016b%016b';
                            }
                            else
                            {
                                $ip = explode('.', $this->ip_address);
                                $sprintf = '%08b%08b%08b%08b';
                            }

                            $ip = vsprintf($sprintf, $ip);
                        }

                        // Split the netmask length off the network address
                        sscanf($proxy_ips[$i], '%[^/]/%d', $netaddr, $masklen);

                        // Again, an IPv6 address is most likely in a compressed form
                        if ($separator === ':')
                        {
                            $netaddr = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($netaddr, ':')), $netaddr));
                            for ($i = 0; $i < 8; $i++)
                            {
                                $netaddr[$i] = intval($netaddr[$i], 16);
                            }
                        }
                        else
                        {
                            $netaddr = explode('.', $netaddr);
                        }

                        // Convert to binary and finally compare
                        if (strncmp($ip, vsprintf($sprintf, $netaddr), $masklen) === 0)
                        {
                            $this->ip_address = $spoof;
                            break;
                        }
                    }
                }
            }

            if ( ! $this->valid_ip($this->ip_address))
            {
                return $this->ip_address = '0.0.0.0';
            }

            return $this->ip_address;
        }
        // --------------------------------------------------------------------

        /**
         * Validate IP Address
         *
         * @param	string	$ip	IP address
         * @param	string	$which	IP protocol: 'ipv4' or 'ipv6'
         * @return	bool
         */
        public function valid_ip($ip, $which = '')
        {
            switch (strtolower($which))
            {
                case 'ipv4':
                    $which = FILTER_FLAG_IPV4;
                    break;
                case 'ipv6':
                    $which = FILTER_FLAG_IPV6;
                    break;
                default:
                    $which = NULL;
                    break;
            }

            return (bool) filter_var($ip, FILTER_VALIDATE_IP, $which);
        }

        // --------------------------------------------------------------------

        /**
         * Fetch User Agent string
         *
         * @return	string|null	User Agent string or NULL if it doesn't exist
         */
        public function user_agent($xss_clean = NULL)
        {
            return $this->_fetch_from_array($_SERVER, 'HTTP_USER_AGENT', $xss_clean);
        }

        // --------------------------------------------------------------------

        /**
         * Sanitize Globals
         *
         * Internal method serving for the following purposes:
         *
         *	- Unsets $_GET data, if query strings are not enabled
         *	- Cleans POST, COOKIE and SERVER data
         * 	- Standardizes newline characters to PHP_EOL
         *
         * @return	void
         */
        protected function _sanitize_globals()
        {
            // Is $_GET data allowed? If not we'll set the $_GET to an empty array
            if ($this->_allow_get_array === FALSE)
            {
                $_GET = array();
            }
            elseif (is_array($_GET))
            {
                foreach ($_GET as $key => $val)
                {
                    $_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
                }
            }

            // Clean $_POST Data
            if (is_array($_POST))
            {
                foreach ($_POST as $key => $val)
                {
                    $_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
                }
            }

            // Clean $_COOKIE Data
            if (is_array($_COOKIE))
            {
                // Also get rid of specially treated cookies that might be set by a server
                // or silly application, that are of no use to a XJ application anyway
                // but that when present will trip our 'Disallowed Key Characters' alarm
                // http://www.ietf.org/rfc/rfc2109.txt
                // note that the key names below are single quoted strings, and are not PHP variables
                unset(
                    $_COOKIE['$Version'],
                    $_COOKIE['$Path'],
                    $_COOKIE['$Domain']
                );

                foreach ($_COOKIE as $key => $val)
                {
                    if (($cookie_key = $this->_clean_input_keys($key)) !== FALSE)
                    {
                        $_COOKIE[$cookie_key] = $this->_clean_input_data($val);
                    }
                    else
                    {
                        unset($_COOKIE[$key]);
                    }
                }
            }

            // Sanitize PHP_SELF
            $_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']);

            //xj_log_message('debug', 'Global POST, GET and COOKIE data sanitized');
        }

        // --------------------------------------------------------------------

        /**
         * Request Headers
         *
         * @return	array
         */
        public function request_headers()
        {
            // If header is already defined, return it immediately
            if ( ! empty($this->headers))
            {
                return $this->headers;
            }

            // In Apache, you can simply call apache_request_headers()
            if (function_exists('apache_request_headers'))
            {
                return $this->headers = apache_request_headers();
            }

            $this->headers['Content-Type'] = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : @getenv('CONTENT_TYPE');

            foreach ($_SERVER as $key => $val)
            {
                if (sscanf($key, 'HTTP_%s', $header) === 1)
                {
                    // take SOME_HEADER and turn it into Some-Header
                    $header = str_replace('_', ' ', strtolower($header));
                    $header = str_replace(' ', '-', ucwords($header));

                    $this->headers[$header] = $this->_fetch_from_array($_SERVER, $key);
                }
            }

            return $this->headers;
        }

        // --------------------------------------------------------------------

        /**
         * Get Request Header
         *
         * Returns the value of a single member of the headers class member
         *
         * @param	string		$index		Header name
         * @return	string|null	The requested header on success or NULL on failure
         */
        public function get_request_header($index)
        {
            static $headers;

            if ( ! isset($headers))
            {
                empty($this->headers) && $this->request_headers();
                foreach ($this->headers as $key => $value)
                {
                    $headers[strtolower($key)] = $value;
                }
            }

            $index = strtolower($index);

            if ( ! isset($headers[$index]))
            {
                return NULL;
            }

            return $headers[$index];
        }

        // --------------------------------------------------------------------

        /**
         * Is AJAX request?
         *
         * Test to see if a request contains the HTTP_X_REQUESTED_WITH header.
         *
         * @return 	bool
         */
        public function is_ajax_request()
        {
            return ( ! empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
        }
        // --------------------------------------------------------------------

        /**
         * Is CLI request?
         *
         * Test to see if a request was made from the command line.
         *
         * @deprecated	3.0.0	Use is_cli() instead
         * @return	bool
         */
        public function is_cli_request()
        {
            return is_cli();
        }
        // --------------------------------------------------------------------

        /**
         * Get Request Method
         *
         * Return the request method
         *
         * @param	bool	$upper	Whether to return in upper or lower case
         *				(default: FALSE)
         * @return 	string
         */
        public function method($upper = FALSE)
        {
            return ($upper)
                ? strtoupper($this->server('REQUEST_METHOD'))
                : strtolower($this->server('REQUEST_METHOD'));
        }

        // ------------------------------------------------------------------------

        /**
         * Magic __get()
         *
         * Allows read access to protected properties
         *
         * @param	string	$name
         * @return	mixed
         */
        public function __get($name)
        {
            if ($name === 'raw_input_stream')
            {
                isset($this->_raw_input_stream) OR $this->_raw_input_stream = file_get_contents('php://input');
                return $this->_raw_input_stream;
            }
            elseif ($name === 'ip_address')
            {
                return $this->ip_address;
            }
        }
    }
}